<template>
  <el-dialog
    :title="!id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="140px"
    >

      <el-form-item label="实验任务名称" prop="experimentId">
        <!--        <el-input v-model="dataForm.task_name" ></el-input>-->
        <el-select v-model="dataForm.experimentId" placeholder="请选择实验任务名称">
          <el-option v-for="(item) in taskData" :key="item.id" :label="item.experimentName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="受试者配合程度" prop="testeeCompliance">
        <!--        <el-input v-model="dataForm.cooperate"></el-input>-->
        <el-select v-model="dataForm.testeeCompliance" placeholder="请选择被试配合程度">
          <el-option label="高" :value="3"></el-option>
          <el-option label="中" :value="2"></el-option>
          <el-option label="低" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主观质量评估" prop="dataQuality">
        <!--        <el-input v-model="dataForm.quality" ></el-input>-->
        <el-select v-model="dataForm.dataQuality" placeholder="请选主观质量评估">
          <el-option label="高" :value="3"></el-option>
          <el-option label="中" :value="2"></el-option>
          <el-option label="低" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="equipmentId">
        <!--        <el-input v-model="dataForm.device" ></el-input>-->
        <el-select v-model="dataForm.equipmentId" filterable placeholder="请选择设备名称">
          <el-option v-for="(item1) in equipmentData" :key="item1.id" :label="item1.equipmentName" :value="item1.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="受试者" prop="testeeNo">
<!--        <el-select v-model="dataForm.testeeNo" placeholder="请选择受试者">-->
<!--          <div class="el-input" style="width:90%;margin-left:5%;">-->
<!--            <input type="text" placeholder="请输入" class="el-input__inner" v-model="dropDownValue" @keyup="dropDownSearch">-->
<!--          </div>-->
<!--          <el-option v-for="(item1) in optionsMetaShow" :key="item1.testeeNo" :label="item1.name+'  编号  '+item1.testeeNo" :value="item1.testeeNo"></el-option>-->
<!--        </el-select>-->
        <el-select v-model="dataForm.testeeNo" filterable placeholder="请选择受试者">
          <el-option v-for="(item1) in optionsMetaShow" :key="item1.testeeNo" :label="item1.name+'  编号  '+item1.testeeNo" :value="item1.testeeNo"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采集阶段" prop="vpCode">
        <!--        <el-input v-model="dataForm.device" ></el-input>-->
        <el-select v-model="dataForm.vpCode" placeholder="请选择采集阶段">
          <el-option v-for="(item1) in v_data" :key="item1.code" :label="item1.name" :value="item1.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="dataForm.description" type="textarea" rows="3"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import uploadFile from '../../api/uploadFile'
import device from '../../api/device'
import task from '../../api/task'
import {ACCEPT_CONFIG} from '@/config';
import SparkMD5 from 'spark-md5';
import uploadfile from "@/api/uploadFile";
import data from '../../api/data'
import subject from '@/api/subject'
import myUtils from '../../api/myUtils'
import research from '@/api/research'
export default {
  data() {
    return {
      dropDownValue: '',
      optionsMetaShow:[],
      visible:true,
      id:0,////尤其要注意这里的id是文件列表的id 不是采集信息单元的id
      dataRule:{
        experimentId: [{ required: true, message: "实验任务不能为空", trigger: "blur" }],
        testeeCompliance: [{ required: true, message: "配合程度不能为空", trigger: "blur" }],
        dataQuality: [{ required: true, message: "主观质量评估不能为空", trigger: "blur" }],
        equipmentId:[{ required: true, message: "实验设备不能为空", trigger: "blur" }],
        testeeNo:[{ required: true, message: "受试者不能为空", trigger: "blur" }],
        vpCode:[{ required: true, message: "采集阶段不能为空", trigger: "blur" }],
      },

      dataForm:{
        id:"1",   //这里的id用来标识显示还是不显示 如果是0的话就不显示了
      },
      taskData:[],
      equipmentData:[],
      v_data:[
        // {
        //   vpCode:'v1',
        //   name:'基线期'
        //
        // },
        // {
        //   vpCode:'v2',
        //   name:'随访1期'
        // }
      ],
      testeeData:[],
      options: {
        //目标上传 URL，默认POST
        target: process.env.BASE_API+"/testee/file/chunk",
        //target:"http://localhost:8090/uploader/chunk",
        //分块大小(单位：字节)
        chunkSize: '2048000',
        //上传文件时文件内容的参数名，对应chunk里的Multipart对象名，默认对象名为file
        fileParameterName: 'upfile',
        //失败后最多自动重试上传次数
        maxChunkRetries: 3,
        //是否开启服务器分片校验，对应GET类型同名的target URL
        testChunks: true,
        /*
        服务器分片校验函数，判断秒传及断点续传,传入的参数是Uploader.Chunk实例以及请求响应信息
        reponse码是successStatuses码时，才会进入该方法
        reponse码如果返回的是permanentErrors 中的状态码，不会进入该方法，直接进入onFileError函数 ，并显示上传失败
        reponse码是其他状态码，不会进入该方法，正常走标准上传
        checkChunkUploadedByResponse函数直接return true的话，不再调用上传接口
        */
        checkChunkUploadedByResponse: function (chunk, response_msg) {
          let objMessage = JSON.parse(response_msg);
          if (objMessage.skipUpload) {
            return true;
          }
          return (objMessage.uploadedChunks || []).indexOf(chunk.offset + 1) >= 0;
        }
      },
      attrs: {
        accept: ACCEPT_CONFIG.getAll()
      },
      fileStatusText: {
        success: '上传成功',
        error: '上传失败',
        uploading: '上传中',
        paused: '暂停',
        waiting: '等待上传'
      },

    }

  },
  created() {
    this.getTask();
    this.geteEuipment();
    this.getTestee();
    this.getVCode()
    // console.log(this.taskData)
    // console.log(this.equipmentData)


  },
  methods:{

    dropDownSearch () {
      //this.dataForm.testeeNo = [];
      // console.log("+++")
      // console.log(this.testeeData)
      // var nameandcode =[]
      // this.testeeData.forEach(item=>{
      //   nameandcode.push(item.name+item.testeeNo)
      // })
      this.optionsMetaShow = this.testeeData.filter(this.filterSearch);
      if(this.optionsMetaShow.length==0)
      {
        this.optionsMetaShow = [{testeeNo:'无',name:'无'}]
      }
    },
    filterSearch (item) {
      let s = item.name+item.testeeNo
      return s.includes(this.dropDownValue);
    },

    init(id)
    {
      this.dataForm = {};
      this.$refs["dataForm"].resetFields();
      //this.$refs["uploader"].resetFields();
      this.id = id || 0;//尤其要注意这里的id是文件列表的id 不是采集信息单元的id
      this.dataForm.id = 0;
      this.dataForm.testeeExperimentFileId = id
      this.visible = true;
      console.log(this.dataForm)
    },

    getVCode()
    {

      research.getBysubjectPkId(this.$route.query.subjectPkId).then((response) => {
        var data = response.data;
        this.v_data = eval(data.vpInfo);//json String格式转成数组对象
        console.log("随访信息")
        console.log(this.v_data)
      })

    },

    getTask()
    {

      task.experimentSearch(this.$route.query.subjectPkId,1,100).then(response => {
        this.taskData = response.data.records

      })


    },
    getTestee()
    {
      subject.testeeSearch2(this.$route.query.subjectPkId,myUtils.getSite(this.$route.query.subjectPkId,this.$store.getters.roles))
      .then(
        (response)=>{
          this.testeeData = response.data.records;
          this.optionsMetaShow = this.testeeData

        }
      )

    },
    geteEuipment()
    {
      //this.$store.getters.site
      device.equipmentSearch(myUtils.getSite(this.$route.query.subjectPkId,this.$store.getters.roles),1,100).then(
        (response)=>{

          this.equipmentData = response.data.records;
        })


    },


    dataFormSubmit()
    {


      {
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.dataForm.createPin = this.$store.getters.name
            this.equipmentData.forEach(
              item=>{
                if(item.id==this.dataForm.equipmentId)
                {
                  this.dataForm.equipmentName = item.equipmentName
                }
              }
            )
            // var strTime="2011-04-16";
            // var date= new Date(Date.parse(strTime.replace(/-/g,  "/")));
            // var formatDate = function (date) {
            //
            //   var y = date.getFullYear();
            //
            //   var m = date.getMonth() + 1;
            //
            //   m = m < 10 ? '0' + m : m;
            //
            //   var d = date.getDate();
            //
            //   d = d < 10 ? ('0' + d) : d;
            //
            //   return y + '-' + m + '-' + d;
            //
            // };
            // this.dataForm.createTime = formatDate(new Date())
            let myDate = new Date();
            this.dataForm.createTime = myDate.toLocaleString();
            this.dataForm.modifyPin = this.$store.getters.name
            this.dataForm.modifyTime = myDate.toLocaleString();
            this.v_data.forEach(
              item =>{
                if(item.vpCode == this.dataForm.vpCode)
                {
                  this.dataForm.vpName = item.name;

                }
              }
            )
            this.taskData.forEach(
              item=>{
                if(item.id == this.dataForm.experimentId)
                {
                  this.dataForm.experimentName = item.experimentName
                  this.dataForm.testeeState = item.testeeState
                }
              }

            )
            this.dataForm.subjectPkId = this.$route.query.subjectPkId

            // this.dataForm.vpCode = this.$store.getters.name
            // this.dataForm.vpName = this.$store.getters.name
            this.dataForm.headerId = 1
            data.updata(this.dataForm).then(({ code }) => {
              if (code  === '000000') {
                uploadFile.updateByid(this.id,1).then(({code})=>
                {
                  if(code === '000000')
                  {
                    this.$message({
                      message: "操作成功",
                      type: "success",
                      duration: 700,
                      onClose: () => {
                        this.visible = false;
                        this.$emit("refreshDataList");
                      }
                    });

                  }
                  else {
                    this.$message.error(data.msg);
                  }

                })



              } else {
                this.$message.error(data.msg);
              }
            });





          }})

      }
      // else{
      //   var formatDate = function (date) {
      //
      //     var y = date.getFullYear();
      //
      //     var m = date.getMonth() + 1;
      //
      //     m = m < 10 ? '0' + m : m;
      //
      //     var d = date.getDate();
      //
      //     d = d < 10 ? ('0' + d) : d;
      //
      //     return y + '-' + m + '-' + d;
      //
      //   };
      //   this.dataForm.subjectPkId = this.$route.query.subjectPkId
      //   this.dataForm.testeeNo = this.$route.query.testeeNo
      //   this.dataForm.headerId = 1
      //   data.updateData(this.dataForm).then(({ code }) => {
      //     if (code  === '000000') {
      //       this.$message({
      //         message: "操作成功",
      //         type: "success",
      //         duration: 700,
      //         onClose: () => {
      //           this.visible = false;
      //           this.$emit("refreshDataList");
      //         }
      //       });
      //     } else {
      //       this.$message.error(data.msg);
      //     }
      //   });
      // }





    },

    onFileProgress(){

    },
    onFileAdded(file) {
      this.computeMD5(file);
    },
    /*
    第一个参数 rootFile 就是成功上传的文件所属的根 Uploader.File 对象，它应该包含或者等于成功上传文件；
    第二个参数 file 就是当前成功的 Uploader.File 对象本身；
    第三个参数就是 message 就是服务端响应内容，永远都是字符串；
    第四个参数 chunk 就是 Uploader.Chunk 实例，它就是该文件的最后一个块实例，如果你想得到请求响应码的话，chunk.xhr.status就是
    */
    onFileSuccess(rootFile, file, response, chunk) {
      //refProjectId为预留字段，可关联附件所属目标，例如所属档案，所属工程等
      file.refProjectId = "123456789";

      this.dataForm.testeeExperimentFileName = file.file.name
      uploadfile.mergeFile(file).then( responseData=> {
        this.dataForm.testeeExperimentFilePath = responseData.data.filePath
        this.dataForm.testeeExperimentFileId = responseData.data.id
        this.dataForm.testeeExperimentFileName = responseData.data.fileName
      }).catch(function (error){
        console.log("合并后捕获的未知异常："+error);
      });
    },
    onFileError(rootFile, file, response, chunk) {
      console.log('上传完成后异常信息：'+response);
    },

    /**
     * 计算md5，实现断点续传及秒传
     * @param file
     */
    computeMD5(file) {
      file.pause();
      //单个文件的大小限制2G
      let fileSizeLimit = 2 * 1024 * 1024 * 1024;
      console.log("文件大小："+file.size);
      console.log("限制大小："+fileSizeLimit);
      if(file.size > fileSizeLimit){
        this.$message({
          showClose: true,
          message: '文件大小不能超过2G'
        });
        file.cancel();
      }
      let fileReader = new FileReader();
      let time = new Date().getTime();
      let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
      let currentChunk = 0;
      const chunkSize = 10 * 1024 * 1000;
      let chunks = Math.ceil(file.size / chunkSize);
      let spark = new SparkMD5.ArrayBuffer();
      //由于计算整个文件的Md5太慢，因此采用只计算第1块文件的md5的方式
      let chunkNumberMD5 = 1;
      loadNext();
      fileReader.onload = (e => {
        spark.append(e.target.result);

        if (currentChunk < chunkNumberMD5) {
          loadNext();
        } else {
          let md5 = spark.end();
          file.uniqueIdentifier = md5;
          file.resume();
          console.log(`MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
        }
      });

      fileReader.onerror = function () {
        this.error(`文件${file.name}读取出错，请检查该文件`)
        file.cancel();
      };

      function loadNext() {
        let start = currentChunk * chunkSize;
        let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
        currentChunk++;
        console.log("计算第"+currentChunk+"块");
      }
    },
    close() {
      this.uploader.cancel();
    },
    error(msg) {
      this.$notify({
        title: '错误',
        message: msg,
        type: 'error',
        duration: 2000
      })
    }


  }


}
</script>
<style>
.uploader-ui {
  padding: 15px;
  margin: 40px auto 0;
  font-size: 12px;
  font-family: Microsoft YaHei;
  box-shadow: 0 0 10px rgba(0, 0, 0, .4);
}
.uploader-ui .uploader-btn {
  margin-right: 4px;
  font-size: 12px;
  border-radius: 3px;
  color: #FFF;
  background-color: #396a94;
  border-color: #409EFF;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
}
.uploader-ui .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}

</style>
